package com.nzd.slsharing.util;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author zzy
 */
public class MailUtil {

    @Resource
    private JavaMailSenderImpl mailSender;

    private String from = "2300161908@qq.com";
    private String to = "18664670663@163.com";


    /**
     * 发送包含简单文本的邮件
     */
    public void sendTxtMail() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //设置收件人，寄件人
        simpleMailMessage.setTo(to);
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setSubject("Spring Boot Mail 邮件测试【文本】");
        simpleMailMessage.setText("这里是一段简单的文本");
        //发送邮件
        mailSender.send(simpleMailMessage);
        System.out.println("邮件已发送");
    }

    /**
     * 发送包含HTML文本的邮件
     *
     * @throws Exception
     */
    public void sendHtmlMail() throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setSubject("Spring Boot Mail 邮件测试【HTML】");

        StringBuilder sb = new StringBuilder();
        sb.append("<html><head></head>");
        sb.append("<body><h1>spring 邮件测试</h1><p>hello!this is spring mail test。</p></body>");
        sb.append("</html>");

        //启动html
        mimeMessageHelper.setText(sb.toString(), true);
        //发送邮件
        mailSender.send(mimeMessage);
        System.out.println("邮件已发送");
    }

    /**
     * 发送包含内嵌图片的邮件
     *
     * @throws Exception
     */
    public void sendAttachedImageMail() throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // multipart模式
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setSubject("Spring Boot Mail 邮件测试【图片】");

        StringBuilder sb = new StringBuilder();
        sb.append("<html><head></head>");
        sb.append("<body><h1>spring 邮件测试</h1><p>hello!this is spring mail test。</p>");
        // cid为固定写法，imageId指定一个标识
        sb.append("<img src=\"cid:imageId\"/></body>");
        sb.append("</html>");

        mimeMessageHelper.setText(sb.toString(), true);
        // 设置imageId
        FileSystemResource img = new FileSystemResource(new File("C:/Users/z2001/Desktop/壁纸/219.png"));
        mimeMessageHelper.addInline("imageId", img);

        mailSender.send(mimeMessage);

        System.out.println("邮件已发送");
    }


}